<template>
  <div>
    <SystemSelect :sub-system="subSystem" @selectChange="selectChange">
      <span>{{ translateTitle('Dams.ApplicationInterface.选择行业') }}:</span>
      <el-select v-model="industryValue" :placeholder="translateTitle('Dams.ApplicationInterface.请选择')" @change="industryChange">
        <el-option v-for="item in industryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </SystemSelect>
    <div class="flex">
      <el-tabs v-model="activeName" class="w-1/2" type="border-card" @tab-click="handleClick">
        <el-tab-pane
          v-for="(v, i) in tabsList"
          :key="i"
          class="p-3 flex"
          :label="v.name + translateTitle('Dams.ApplicationInterface.菜单')"
          :name="v.name"
        >
          <div class="w-full">
            <vxe-table
              ref="xTableTree"
              align="center"
              border
              :column-config="{ resizable: true, isCurrent: true, isHover: true }"
              :data="v.treeData"
              :height="`${Number(getHeight) - 131}`"
              :keep-source="true"
              :row-config="{ isCurrent: true, isHover: true }"
              :show-overflow="true"
              :tree-config="tableTreeConfig"
              @cell-click="clickOne"
            >
              <vxe-column field="MENU_NAME" :title="translateTitle('Dams.ApplicationInterface.菜单名称')" tree-node />
              <vxe-column field="LANGUAGE_CODE" :title="translateTitle('Dams.ApplicationInterface.语言类型')" />
              <vxe-column field="SORT" :title="translateTitle('Dams.ApplicationInterface.菜单排序')" />
            </vxe-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div class="w-1/2">
        <el-tabs v-model="translateName" :before-leave="languagesSelectChange" type="border-card">
          <el-tab-pane :label="translateTitle('Dams.ApplicationInterface.菜单翻译')" name="menu">
            <div v-if="languageOptions.length > 0">
              <div class="menu-translate overflow-y-auto" :style="{ height: `${Number(getHeight) - 131}px` }">
                <div class="title">
                  <div class="w-1/2 text-center">{{ translateTitle('Dams.ApplicationInterface.语言类型') }}</div>
                  <div class="w-1/2 text-center">{{ translateTitle('Dams.ApplicationInterface.翻译项') }}</div>
                </div>
                <div v-for="(v, i) in languageOptions" :key="i" class="menu-translate-item">
                  <div class="w-1/2 flex justify-center items-center">{{ v.LANGUAGE_DESC }}</div>
                  <div class="w-1/2">
                    <el-input v-model="v.TRANSLATION_CONTENT" clearable :disabled="v.LANGUAGE_CODE == 'zh_CN'" />
                  </div>
                </div>
              </div>
              <el-button type="primary" @click="saveTranslationMenu">{{ translateTitle('Dams.ApplicationInterface.保存') }}</el-button>
            </div>
            <div v-else class="text-center" :style="{ height: `${Number(getHeight) - 107}px` }">
              {{ translateTitle('Dams.ApplicationInterface.暂无数据') }}
            </div>
          </el-tab-pane>
          <el-tab-pane v-if="!isSuperior" :disabled="!meunId" :label="translateTitle('Dams.ApplicationInterface.列表内容翻译')" name="jsonContent">
            <div>
              <el-button @click="downloadJson">{{ translateTitle('Dams.ApplicationInterface.导出') }}</el-button>
              <div class="ml-0.5 inline-block">
                <el-upload accept=".xlsx, .xls" action="#" :before-upload="uploadHandleClick" :limit="1">
                  <el-button size="small" type="primary">{{ translateTitle('Dams.ApplicationInterface.点击上传') }}</el-button>
                </el-upload>
              </div>
            </div>
            <p style="color: red">
              {{
                `${translateTitle('Dams.ApplicationInterface.翻译前需要去拖拽页面保存下')}(2022.9.6)。${translateTitle(
                  'Dams.ApplicationInterface.而且前面如果有其他语种的需要删除'
                )}(2022.9.6${translateTitle('Dams.ApplicationInterface.之前的')})`
              }}
            </p>
            <div>
              <div class="flex">
                <div key="content_json" class="w-1/2">
                  <vxe-table
                    v-if="!isSuperior"
                    ref="xTable2"
                    border
                    :data="jsonList"
                    :height="`${Number(getHeight) - 169}`"
                    :radio-config="{ labelField: 'showtext' }"
                    :scroll-y="{ scrollToTopOnChange: true, gt: 50 }"
                    @radio-change="radioChange"
                  >
                    <vxe-column :title="translateTitle('Dams.ApplicationInterface.列表内容项')" type="radio" />
                  </vxe-table>
                </div>
                <div class="w-1/2">
                  <JsonList :list="contentOptions" />
                </div>
              </div>
              <el-button type="primary" @click="saveTranslationJson">{{ translateTitle('Dams.ApplicationInterface.保存') }}</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script>
  import debounce from 'lodash/debounce'
  import cloneDeep from 'lodash/cloneDeep'
  import { getList } from '../../api/home'
  import { GFCD } from '@/utils/utils'
  import SystemSelect from '../../components/systemSelect.vue'
  import JsonList from '../../components/jsonList.vue'
  import { export_json_to_excel } from '@ve/utils/exportExcel'
  import { getComponentsAll } from '@ve/utils/translateTools'
  //extendLanguage
  import { translateTitle } from '@/utils/i18n'
  import { isArray } from '@/utils/validate'

  const XLSX = require('xlsx')
  export default {
    name: 'BusinessSystemTranslation',
    components: {
      SystemSelect,
      JsonList,
    },
    data() {
      return {
        translateName: 'menu',
        tabsList: [],
        dialogVisible: false,
        tableTreeConfig: {
          transform: true,
          rowField: 'ID',
          parentField: 'PID',
        },
        clientHeight: 0,
        configSetting: {},
        translateData: [],
        oldPageJson: {},
        meunId: '',
        meunName: '',
        languageOptions: [],
        languageForm: {
          value: '',
        },
        subSystem: 'WMS',
        languageValue: 'zh_CN',
        tabsIndex: 0,
        activeName: 'PC',
        industryOptions: [
          { value: '1', label: translateTitle('Dams.ApplicationInterface.标准行业') },
          { value: '2', label: translateTitle('Dams.ApplicationInterface.医药行业') },
          { value: '3', label: translateTitle('Dams.ApplicationInterface.水酒行业') },
        ],
        industryValue: '1',
        jsonList: [],
        contentOptions: [],
        menuOpen: false,
        isSuperior: true,
        excelHeader: [],
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 100}`
      },
    },
    created() {
      let systemOptions = cloneDeep(this.$store.getters['user/apps'])
      let index = systemOptions.findIndex((el) => el.APP_CODE == 'DAMS')
      if (index > -1) {
        systemOptions.splice(index, 1)
      }
      let index1 = systemOptions.findIndex((el) => el.APP_CODE == 'BQMS')
      if (index1 > -1) {
        systemOptions.splice(index1, 1)
      }
      this.subSystem = systemOptions[0].APP_CODE
      this.init()
    },
    methods: {
      translateTitle,
      getHeaderRow(sheet) {
        const headers = []
        const range = XLSX.utils.decode_range(sheet['!ref'])
        let C
        const R = range.s.r
        for (C = range.s.c; C <= range.e.c; ++C) {
          const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
          let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
          if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
          headers.push(hdr)
        }
        return headers
      },
      uploadHandleClick(e) {
        console.log(e)
        // const files = e.target.files
        const reader = new FileReader()
        reader.onload = (e) => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          console.log(header, results)
          if (!(header.length === this.excelHeader.length && header.filter((t) => !this.excelHeader.includes(t))))
            return this.$baseMessage(translateTitle('Dams.ApplicationInterface.导入数据错误'), 'error')
          this.jsonList.forEach((r) => {
            if (results.find((el) => el.ID == r._id)) {
              r.languageList.forEach((row) => {
                row.TRANSLATION_CONTENT = results.find((el) => el.ID == r._id)[row.LANGUAGE_DESC]
              })
            }
          })
          // this.$baseMessage(translateTitle('Dams.ApplicationInterface.上传成功'), 'success')
          this.submitJson()
          console.log(this.jsonList)
        }
        reader.readAsArrayBuffer(e)
      },
      //json格式化
      formatJson(filterVal, jsonData) {
        jsonData.map((v) => filterVal.map((j) => (v[j] ? v[j] : '')))
        return jsonData.map((v) => filterVal.map((j) => (v[j] ? v[j] : '')))
      },
      downloadJson() {
        console.log(this.jsonList)
        let list = []
        this.jsonList.forEach((r) => {
          let obj = {}
          r.languageList.forEach((row) => {
            obj[row.LANGUAGE_CODE] = row.TRANSLATION_CONTENT
          })
          list.push({ id: r._id, ...obj })
        })
        console.log(list)
        let multiHeader = ['ID']
        let filterVal = ['id']
        this.languageOptions.forEach((r) => {
          multiHeader.push(r.LANGUAGE_DESC)
          filterVal.push(r.LANGUAGE_CODE)
        })
        let data = this.formatJson(filterVal, list)
        console.log(data)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          data, //数据
          // filename: translateTitle('Dams.ApplicationInterface.导出文件JSON') + '_' + new Date().getTime(),
          filename: this.languageOptions.find((el) => el.LANGUAGE_CODE == 'zh_CN').TRANSLATION_CONTENT + '_' + new Date().getTime(),
          bookType: 'xlsx',
        })
      },
      industryChange() {
        this.getTree()
      },
      handleClick(e) {
        this.tabsIndex = e.index
      },
      selectChange(val) {
        this.subSystem = val
        this.init()
        this.meunId = ''
        this.tabsIndex = 0
        this.activeName = this.tabsList[0].name
        this.tabsList[this.tabsIndex].translateData = []
        this.tabsList[this.tabsIndex].oldPageJson = []
      },
      languagesSelectChange(name) {
        console.log(name)
        let tojump = false
        this.languageOptions.forEach((r) => {
          if (!r.TRANSLATION_CONTENT) {
            tojump = true
          }
        })
        if (name == 'jsonContent') {
          if (tojump && !this.menuOpen) {
            this.$baseMessage(translateTitle('Dams.ApplicationInterface.请将菜单翻译保存完再点击内容翻译'), 'error')
            return false
          }
        }
      },
      saveTranslationJson() {
        this.$confirm(translateTitle('Dams.ApplicationInterface.请确认翻译项已经全部翻译') + '?', translateTitle('Dams.ApplicationInterface.提示'), {
          confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
          cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
          type: 'warning',
        })
          .then(() => {
            this.submitJson()
          })
          .catch(() => {
            return false
          })
      },
      radioChange({ row }) {
        row.languageList.forEach((r, i) => {
          r.numIndex = row.num + '' + i
        })
        this.contentOptions = row.languageList
      },
      async submitJson() {
        let num = this.jsonList[0].languageList.length
        let list = []
        // let newPageJson = cloneDeep(this.languageOptions.find((el) => el.LANGUAGE_CODE == 'zh_CN').PAGE_JSON)
        console.log(this.jsonList)
        for (let index = 0; index < num; index++) {
          list.push({
            pageJson: [],
            // pageJson: JSON.parse(newPageJson),
            language: this.jsonList[0].languageList[index].LANGUAGE_CODE,
            menuName: this.languageOptions[index].TRANSLATION_CONTENT,
            LANGUAGE_CODE: this.languageOptions[index].LANGUAGE_CODE,
          })
        }
        list.forEach((r, i) => {
          this.jsonList.forEach((row) => {
            if (r.LANGUAGE_CODE != 'zh_CN') {
              r.pageJson.push({ showtext: row.languageList[i].TRANSLATION_CONTENT, _id: row._id })
            }
          })
        })
        console.log(cloneDeep(list))
        // list.forEach((r) => {
        //   let oldJson = cloneDeep(r.pageJson)
        //   extendLanguage(oldJson, r.json)
        //   r.pageJson = oldJson
        // })
        let subList = []
        list.forEach((r) => {
          if (r.LANGUAGE_CODE != 'zh_CN') {
            subList.push({
              MENU_CODE: this.meunId,
              PAGE_JSON: JSON.stringify(r.pageJson),
              MENU_NAME: r.menuName,
              LANGUAGE_CODE: r.LANGUAGE_CODE,
              BUSINESS_TYPE: this.industryValue,
              BUSINESS_TYPE_NAME: this.industryOptions.find((el) => el.value == this.industryValue).label,
            })
          }
        })
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify({
            menuPage: subList,
            APP_CODE: this.subSystem,
          }),
          method: 'sysPageServiceImpl.saveTranslationPageJson',
        })
        this.$baseMessage(translateTitle('Dams.ApplicationInterface.保存成功'), 'success')
        console.log(res)
      },
      async saveTranslationMenu() {
        let list = []
        let required = false
        this.languageOptions.forEach((res) => {
          if (!res.TRANSLATION_CONTENT) {
            required = true
          }
          if (res.TRANSLATION_CONTENT) {
            list.push({
              LANGUAGE_CODE: res.LANGUAGE_CODE,
              TRANSLATION_CONTENT: res.TRANSLATION_CONTENT,
            })
          }
        })
        if (required) return this.$baseMessage(translateTitle('Dams.ApplicationInterface.请将翻译项填写完整'), 'error')
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify({ MENUS: list, APP_CODE: this.subSystem, MENU_CODE: this.meunId }),
          method: 'sysPageServiceImpl.translateMenuSave',
        })
        this.menuOpen = true
        this.$baseMessage(translateTitle('Dams.ApplicationInterface.保存成功'), 'success')
        console.log(res)
      },
      async getLanguage() {
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify({ APP_CODE: this.subSystem, MENU_CODE: this.meunId ? this.meunId : 'L1001', BUSINESS_TYPE: this.industryValue }),
          method: 'sysPageServiceImpl.queryLanguageForPage',
        })
        console.log(res)
        this.languageOptions = cloneDeep(res.data)
        this.languageOptions.forEach((r) => {
          delete r.PAGE_JSON
        })
        this.excelHeader = ['ID']
        const testList = res.data
        testList.forEach((r) => {
          this.excelHeader.push(r.LANGUAGE_DESC)
          if (!r.TRANSLATION_CONTENT) {
            r.TRANSLATION_CONTENT = ''
          }
          r.MENU_CODE = this.meunId
          if (r.LANGUAGE_CODE == 'zh_CN') {
            r.pageJson = testList.find((el) => el.LANGUAGE_CODE == r.LANGUAGE_CODE).PAGE_JSON
              ? getComponentsAll(
                  testList.find((el) => el.LANGUAGE_CODE == r.LANGUAGE_CODE).PAGE_JSON,
                  testList.find((el) => el.LANGUAGE_CODE == 'zh_CN').pageJson
                )
              : ''
          }
          if (r.LANGUAGE_CODE != 'zh_CN') {
            r.pageJson = testList.find((el) => el.LANGUAGE_CODE == r.LANGUAGE_CODE).PAGE_JSON
              ? JSON.parse(testList.find((el) => el.LANGUAGE_CODE == r.LANGUAGE_CODE).PAGE_JSON)
              : ''
          }
        })
        let languageList = cloneDeep(testList)
        languageList.forEach((r) => {
          delete r.PAGE_JSON
          delete r.pageJson
          r.TRANSLATION_CONTENT = ''
        })
        console.log(this.languageOptions)
        let json = testList.find((el) => el.LANGUAGE_CODE == 'zh_CN').pageJson
        if (json.components && json.components.length > 0) {
          json.components.forEach((r, i) => {
            r.languageList = cloneDeep(languageList)
            r.num = i
            r.languageList.forEach((v, index) => {
              if (
                testList.find((el) => el.LANGUAGE_CODE == v.LANGUAGE_CODE) &&
                testList.find((el) => el.LANGUAGE_CODE == v.LANGUAGE_CODE).PAGE_JSON
              ) {
                let newPageJson = testList[index].pageJson
                if (v.LANGUAGE_CODE == 'zh_CN') {
                  v.TRANSLATION_CONTENT =
                    newPageJson && newPageJson.components.find((el) => el._id == r._id)
                      ? newPageJson.components.find((el) => el._id == r._id).showtext
                      : ''
                } else {
                  v.TRANSLATION_CONTENT =
                    newPageJson && isArray(newPageJson) && newPageJson.find((el) => el._id == r._id)
                      ? newPageJson.find((el) => el._id == r._id).showtext
                      : ''
                }
              }
            })
          })
          this.jsonList = json.components
          console.log(this.jsonList)
        }
      },
      windowResize: debounce(function () {
        console.log('document.documentElement.clientHeight', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      init() {
        // this.configSetting = GFCD(this.subSystem.toLocaleLowerCase())
        this.windowResize()
        this.configSetting = GFCD('dams')
        this.getTree()
        // this.getLanguage()
      },
      clickOne(e) {
        let _this = this
        let curTime = new Date().getTime()
        let lastTime = _this.lastTapDiffTime
        _this.lastTapDiffTime = curTime
        //两次点击间隔小于300ms, 认为是双击
        console.log(e)
        let diff = curTime - lastTime
        if (diff < 300) {
          // if (!e.row.PID || e.row.PID == '100') return
          if (e.row.PID && e.row.children.length == 0) {
            this.isSuperior = false
          } else {
            this.isSuperior = true
          }
          this.meunName = e.row.MENU_NAME
          this.meunId = e.row.ID
          this.tabsList[this.tabsIndex].meunId = e.row.ID
          this.tabsList[this.tabsIndex].meunName = e.row.MENU_NAME
          this.getLanguage(e.row.ID)
          this.translateName = 'menu'
          this.menuOpen = false
          this.contentOptions = []
        }
      },
      getRecursionTree(list, pid) {
        // if()
        return list.reduce((res, current) => {
          if (current['PID'] === pid) {
            current.children = this.getRecursionTree(list, current['ID'])
            return res.concat(current)
          }
          return res
        }, [])
      },
      getTreeType(item) {
        console.log('item', item)
        // item.allPageJson.forEach((r) => {
        //   r.label = r.BUSINESS_TYPE_NAME
        //   r.PID = r.MENU_CODE
        //   r.ID = r.MENU_CODE + r.LANGUAGE_CODE + r.BUSINESS_TYPE
        //   r.value = r.ID
        //   r.disabled = true
        // })
        let pageJson = []
        item.allMenu.forEach((r) => {
          r.value = r.ID
          r.label = r.MENU_NAME
          // if (item.allPageJson.find((el) => el.PID == r.ID)) {
          //   item.allPageJson.find((el) => el.PID == r.ID).TYPE = r.TYPE
          //   pageJson.push(item.allPageJson.find((el) => el.PID == r.ID))
          // }
        })
        item.first = this.getRecursionTree(item.allMenu, '')
        console.log(this.getRecursionTree(item.allMenu, ''))
        let arr = item.allMenu.concat(pageJson)
        arr = arr.sort((a, b) => {
          return a.SORT - b.SORT
        })
        console.log(cloneDeep(arr))
        return arr
      },
      async getTree() {
        let p = {}
        let method
        p = {
          SUB_SYSTEM: this.subSystem,
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 9999,
          APP_CODE: this.subSystem,
          BUSINESS_TYPE: this.industryValue,
          LANGUAGE_CODE: 'zh_CN',
        }
        method = 'sysPageServiceImpl.standardPageQueryMultistage'
        // p.LANGUAGE_CODE = this.$store.getters['user/language']
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(p),
          method: method,
        })
        console.log(res.data)
        let list = []
        for (const key in res.data) {
          const element = res.data[key]
          list.push({
            name: key,
            treeData: this.getTreeType(element),
            languageValue: 'zh_CN',
            translateData: [],
            oldPageJson: [],
            meunId: '',
            meunName: '',
          })
        }
        this.tabsList = list
        console.log(this.tabsList)
        // this.activeName = this.tabsList[0].name
      },
    },
  }
</script>
<style lang="scss">
  @import '@/ve/elements/basic/uiTable/style.scss';
  @import '@/ve/styles/elements.scss';
  .vxe-button + .vxe-button,
  .vxe-button.type--text {
    margin-left: 0;
    font-size: 12px;
  }
  .vxe-button--content {
    vertical-align: baseline;
  }
</style>
<style lang="scss" scoped>
  .menu-translate {
    width: 100%;
    .title {
      font-weight: 600;
    }
    .title,
    .menu-translate-item {
      display: flex;
      // justify-content: space-around;
      padding: 5px 0;
      border-bottom: 1px solid #edeef2;
    }
  }
  :deep() {
    .el-upload-list {
      display: none;
    }
  }
</style>
